package oa.hleast.xswl.common.annotation;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.result.ResultCode;
import oa.hleast.common.web.exception.BizException;
import oa.hleast.common.web.util.RequestUtils;
import oa.hleast.xswl.pojo.dto.UmsUserDto;
import oa.hleast.xswl.service.IUmsUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class UserAuthAspect {

    private final IUmsUserService umsUserService;

    @Pointcut(value = "@annotation(oa.hleast.xswl.common.annotation.UserAuth)")
    public void access() {

    }

    @Before("access()")
    public void doBefore(JoinPoint joinPoint)  {
        try{
            Long userId = RequestUtils.getUserId();
            UmsUserDto userResult = umsUserService.getUserDtoById(userId);
            if (ObjectUtils.isEmpty(userResult) || ObjectUtils.isEmpty(userResult.getId())) {
                throw new BizException(ResultCode.USER_NOT_EXIST);
            }
        }catch (Exception e){
            log.error("用户不存在",e);
            throw new BizException(ResultCode.USER_NOT_EXIST);
        }

    }


    @Around("@annotation(oa.hleast.xswl.common.annotation.UserAuth)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        return pjp.proceed();

    }


    @After("access()")
    public void after(JoinPoint joinPoint) {
    }

}